var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
const { ohana } = require("ohana-node-orm");
const ohana_instance = new ohana("SAP_JIANGDU_WORKTABLE");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");
const moment = require("moment");
const ohana_policy = new ohana("SAP_JIANGDU_TAG_POLICYS");

router.get("/convertCaijingyun", (req, res) => {
    // #swagger.tags = ['财经云']
    // #swagger.summary = '财经云数据转换 到policy'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    log.info("Start to transfer financial cloud data");
    convertCaijingyun();
    res.status(200).send("Start to transfer financial cloud data\n");
});

async function convertCaijingyun() {
    let stringText = "select * from  CAIJINGYUN_INTEGRATION";
    let result = await ohana_policy.raw(stringText);
    let count = 0;
    for (let index = 0; index < result.length; index++) {
        const element = result[index];
        let DATA = JSON.parse(element["CAIJINGYUN_INTEGRATION"]).DATA;
        DATA.forEach((data) => {
            if (data.MATTERNAME) {
                let insertData = {};
                insertData.POLICY_ID = uunewid.v4();
                insertData.POLICY_TITLE = data.MATTERNAME;
                if (data.ACCORDING) {
                    insertData.CDATA = data.ACCORDING;
                }
                insertData.CREATED_AT = moment(new Date()).format(
                    "YYYY-MM-DD HH:mm:ss"
                );
                insertData.UPDATED_AT = moment(new Date()).format(
                    "yyyy-MM-DD HH:mm:ss"
                );
                console.log(insertData);
                ohana_policy.insert(insertData);
                count++;
            }
        });
    }
    log.info("成功插入" + count + "条政策\n");
}

//创建文件表答案
router.post("/", async (req, res, next) => {
    // #swagger.tags = ['财经云']
    // #swagger.summary = '文件列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                required: true,
                content: {
                    "application/json": {
                        schema: {
                            $ref: "#/definitions/questionnaire"
                        }  
                    },
                }
        } */

    /***
     * insertJsonDoc
     *   {
     *  ID:"五大服务的ID"
     *  detail：[] fileList
     * }
     *
     */
    const { data } = req.body;
    const result = await insertJsonDoc(data);
    if (result == 1) {
        res.sendStatus(200);
    } else {
        res.sendStatus(500);
    }
});

router.get("/", async (req, res, next) => {
    // #swagger.tags = ['财经云']
    // #swagger.summary = '获得数据'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /* #swagger.parameters['ID'] = {
            description: 'ID',
            required: true,
            type: 'string',
      } */
    const { ID } = req.query;
    const result = await getJsonDoc(ID);
    res.send(result);
});

//更新文件表 只能更新Answers
/**
{
    "data":{"ANSWERS": {"TEST": "132", "COOL": "it works"}, "UUID": "455bdad0-4cbb-4bc4-85b0-0c34c0e4d8c4"}
}
**/
router.put("/", async (req, res, next) => {
    // #swagger.tags = ['财经云']
    // #swagger.summary = '更新questionnaire'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                required: true,
                content: {
                    "application/json": {
                        schema: {
                            $ref: "#/definitions/questionnaire_update"
                        }  
                    },
                }
        } */
    const { data } = req.body;
    const result = await updateJsonDoc(data);
    if (result == 1) {
        res.sendStatus(200);
    } else {
        res.sendStatus(500);
    }
});

/*
 *删除文件表id
 */

router.delete("/", async (req, res, next) => {
    // #swagger.tags = ['财经云']
    // #swagger.summary = '删除questionnaire'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
              required: true,
              content: {
                  "application/json": {
                      schema: {
                          $ref: "#/definitions/caijingyun_delete"
                      }  
                  },
              }
      } */
    const { data } = req.body;
    const result = await deleteJsonDoc(data);

    if (result == 1) {
        res.sendStatus(200);
    } else {
        res.sendStatus(500);
    }
});

async function insertJsonDoc(data) {
    var json = JSON.stringify(data); // {"type":"Fiat","model":"500","color":"White"}为了去掉"符合HANA json 插入的格式
    var unquoted = json.replace(/"([^"]+)":/g, "$1:");
    let resultText = unquoted.replace(new RegExp('"', "g"), "'");
    var stringText =
        "insert into CAIJINGYUN_INTEGRATION values(" + resultText + ")";
    const result = await ohana_instance.raw(stringText);
    return result;
}
async function getJsonDoc(ID) {
    let stringText =
        "select * from  CAIJINGYUN_INTEGRATION where META.BATCH_ID = '" + ID + "'";
    let result = await ohana_instance.raw(stringText);

    if (result.length > 0) {
        return JSON.parse(result[0]["CAIJINGYUN_INTEGRATION"]);
    } else {
        return { message: "没有对应ID的数据" };
    }
}

async function updateJsonDoc(data) {
    var json = JSON.stringify(data.DETAIL_FILELIST); // {"type":"Fiat","model":"500","color":"White"}为了去掉"符合HANA json 插入的格式
    var unquoted = json.replace(/"([^"]+)":/g, "$1:");
    let resultText = unquoted.replace(new RegExp('"', "g"), "'");
    var stringText =
        "update CAIJINGYUN_INTEGRATION SET DETAIL_FILELIST = " +
        resultText +
        " where ID = '" +
        data.ID +
        "'";
    const result = await ohana_instance.raw(stringText);
    return result;
}

async function deleteJsonDoc(data) {
    var stringText =
        "delete from  CAIJINGYUN_INTEGRATION where META.BATCH_ID = '" +
        data.ID +
        "'";
    const result = await ohana_instance.raw(stringText);
    return result;
}

module.exports = router;
